package com.daocao.jy.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.jy.R;
import com.daocao.jy.adapter.PacketTypeAdapter;
import com.daocao.jy.api.Api;
import com.daocao.jy.api.bean.PaymentBean;
import com.daocao.jy.api.bean.RechargeTermDetailBean;
import com.daocao.jy.api.bean.RechargeTermOrderBean;
import com.daocao.jy.base.BaseActivity;
import com.daocao.jy.constant.Const;
import com.daocao.jy.util.Dialog;
import com.daocao.jy.util.Network;
import com.daocao.jy.util.RxLifeUtil;
import com.daocao.jy.util.ToastUtil;
import com.daocao.jy.util.UI;
import com.daocao.jy.util.Util;
import com.daocao.jy.view.OilChangeDialog;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class PacketRechargeActivity extends BaseActivity {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.list_type)
    RecyclerView listType;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.layout_empty_oilcard)
    LinearLayout layoutEmptyOilcard;
    @BindView(R.id.layout_has_oilcard)
    RelativeLayout layoutHasOilcard;
    @BindView(R.id.txt_recharge_total)
    TextView txtRechargeTotal;
    @BindView(R.id.txt_actual_total)
    TextView txtActualTotal;
    @BindView(R.id.txt_recharge_tips)
    TextView txtRechargeTips;
    @BindView(R.id.txt_oil_type)
    TextView txtOilType;
    @BindView(R.id.txt_oil_card)
    TextView txtOilCard;
    @BindView(R.id.txt_term_detail)
    TextView txtTermDetail;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    private Unbinder unbiner;
    private PacketTypeAdapter adapter;
    private OilChangeDialog oilChangeDialog;
    private String select_id;
    private String paymentType;
    private String select_oilcard_id;
    private String select_money_total;
    private String select_actual_money;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;
    private String selectWays;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
    private static final String ACCOUNT = "BAG";
    private float period_cal;
    private float sale_cal;
    private boolean isCheckAll = false;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_packet);
        initWebViewBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("套餐充值");
        txtRechargeTotal.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        oilChangeDialog = new OilChangeDialog(this);
        oilChangeDialog.setDialogClickListener(new OilChangeDialog.DialogDefaultClickListener() {
            @Override
            public void confirm(String id, String ctype, String card_number) {
                select_oilcard_id = id;
                if (ctype.equals("1")) {
                    txtOilType.setText("中国石化");
                    imgIcon.setImageResource(R.mipmap.img_recharge_shihua);
                } else if (ctype.equals("2")) {
                    txtOilType.setText("中国石油");
                    imgIcon.setImageResource(R.mipmap.img_recharge_shiyou);
                }
                txtOilCard.setText(card_number);
            }

            @Override
            public void cancel() {

            }
        });
        listType.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new PacketTypeAdapter(this);
        adapter.setOnChooseListener(new PacketTypeAdapter.OnChooseListener() {
            @Override
            public void onClick(float period, float sale, String id) {
                period_cal = period;
                sale_cal = sale;
                select_id = id;
                getCalculate();
            }
        });
        listType.setAdapter(adapter);
        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getCalculate();
            }
        });


        initPay();
        mHandler = new PayHandler(this);
        getRechargeTerm();
        getOilCardList();
    }


    //    ===========================获取支付方式===========================
    public void getPaymentList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        Api.api_service.getPaymentList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showRechargeTypeDialog(this, result.datas, new Dialog.DialogPaymentClickListener() {
                        @Override
                        public void confirm(String name, String id) {
                            selectWays = name;
                            paymentType = id;
                            getRechargeTermOrder(select_id, "0", UI.toString(editMoney), select_oilcard_id, paymentType);
                        }

                    });
                });
    }
    //    ===========================获取支付方式===========================

    //    ===========================余额支付===========================
    public void getBagPayment(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        PaymentBean bean = new PaymentBean();
        bean.order_no = order_no;
        Api.api_service.getBagPayment(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "支付成功");
                });
    }
    //    ===========================余额支付===========================


    //    ===========================获取分期列表===========================
    public void getRechargeTerm() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        Api.api_service.getRechargeTerm().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.update(result.datas);
                });
    }
    //    ===========================获取分期列表===========================


    //    ===========================获取分期详情===========================
    public void getRechargeTermDetail(String combo_id, String term_money) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        RechargeTermDetailBean bean = new RechargeTermDetailBean();
        bean.combo_id = combo_id;
        bean.term_money = term_money;
        Api.api_service.getRechargeTermDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showRechargeDetailDialog(this, result.datas, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {

                        }

                        @Override
                        public void cancel() {

                        }
                    });
                });
    }
    //    ===========================获取分期详情===========================


    //    ===========================获取油卡列表===========================
    public void getOilCardList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        Api.api_service.getOilcardList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (isCheckAll) {
                        oilChangeDialog.setData(result.datas);
                        oilChangeDialog.show();
                        return;
                    }
                    if (result.datas != null && result.datas.size() != 0) {
                        layoutHasOilcard.setVisibility(View.VISIBLE);
                        layoutEmptyOilcard.setVisibility(View.GONE);
                        select_oilcard_id = result.datas.get(0).id;
                        if (result.datas.get(0).ctype.equals("1")) {
                            txtOilType.setText("中国石化");
                            imgIcon.setImageResource(R.mipmap.img_recharge_shihua);
                        } else if (result.datas.get(0).ctype.equals("2")) {
                            txtOilType.setText("中国石油");
                            imgIcon.setImageResource(R.mipmap.img_recharge_shiyou);
                        }
                        txtOilCard.setText(result.datas.get(0).card_number);
                    } else {
                        layoutHasOilcard.setVisibility(View.GONE);
                        layoutEmptyOilcard.setVisibility(View.VISIBLE);
                    }

                });
    }
    //    ===========================获取油卡列表===========================


    //    ===========================获取分期订单===========================
    public void getRechargeTermOrder(String combo_id, String coupon_id, String money, String oilcard_id, String pay_way) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        RechargeTermOrderBean bean = new RechargeTermOrderBean();
        bean.combo_id = combo_id;
        bean.coupon_id = coupon_id;
        bean.money = money;
        bean.oilcard_id = oilcard_id;
        bean.pay_way = pay_way;
        Api.api_service.getRechargeTermOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (selectWays.equals(ACCOUNT)) {
                        getBagPayment(result.datas.order_no);
                    } else {
                        goToPay("支付", result.datas.money, result.datas.order_no);
                    }
                });
    }
    //    ===========================获取分期订单===========================

    //    ===========================计算套餐所需金额===========================
    private void getCalculate() {
        if (TextUtils.isEmpty(select_id)) {
            ToastUtil.makeText(this, "请选择分期套餐");
            return;
        }
        if (TextUtils.isEmpty(UI.toString(editMoney))) {
            ToastUtil.makeText(this, "请输入金额");
            return;
        }
        float numMoneyTotal = UI.toFloat(editMoney) * period_cal;


        float numMoney = UI.toFloat(editMoney) * period_cal * (sale_cal / 100);
        BigDecimal numMoney_bd = new BigDecimal(numMoney);
        numMoney_bd = numMoney_bd.setScale(1, BigDecimal.ROUND_HALF_UP);

        float zhekou = numMoneyTotal - numMoney;
        BigDecimal zhekou_bd = new BigDecimal(zhekou);
        zhekou_bd = zhekou_bd.setScale(1, BigDecimal.ROUND_HALF_UP);
        txtRechargeTotal.setText("￥" + numMoneyTotal);
        txtActualTotal.setText("￥" + numMoney_bd);
        UI.setTvHtml(txtRechargeTips, R.string.money_packet, numMoneyTotal, numMoney_bd, zhekou_bd);

        txtTermDetail.setText(UI.toString(editMoney) + "元/月*" + period_cal + "个月=" + numMoneyTotal + "元");
    }
//    ===========================计算套餐所需金额===========================

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_oil_change, R.id.btn_tips,R.id.btn_back})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_oil_change:
                isCheckAll = true;
                getOilCardList();
                break;
            case R.id.btn_tips:
                Util.startActivity(this, VipPacketActivity.class);
                break;
            case R.id.btn_back:
                finish();
                break;
        }

    }

    @OnClick(R.id.btn_recharge_detail)
    public void onViewClicked1() {
        getRechargeTermDetail(select_id, UI.toString(editMoney));
    }

    @OnClick(R.id.btn_recharge)
    public void onViewClicked2() {
        getPaymentList();
    }

    @OnClick({R.id.btn_sub, R.id.btn_add})
    public void onViewClicked(View view) {
        if (TextUtils.isEmpty(select_id)) {
            ToastUtil.makeText(this, "请选择分期套餐");
            return;
        }
        if (TextUtils.isEmpty(UI.toString(editMoney))) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_sub:

                if (UI.toInteger(editMoney) < 100) {
                    return;
                }
                editMoney.setText((UI.toInteger(editMoney) - 100) + "");
                break;
            case R.id.btn_add:
                editMoney.setText((UI.toInteger(editMoney) + 100) + "");
                break;
        }
    }


    private void initPay() {
        // 推荐在主Activity或application里的onCreate函数中初始化BeeCloud.
//        if (!Const.IS_DEBUG) {
//            BeeCloud.setSandbox(true);
//
////        测试Appid和secret
//            BeeCloud.setAppIdAndSecret("956fb30c-0579-4469-aa31-64140d64e61c",
//                    "e32e1f0d-d219-4c76-8585-13f953327123");
//        } else {
        BeeCloud.setSandbox(false);
        //     正式网Appid和secret
        BeeCloud.setAppIdAndSecret(Const.BeeCloud.APP_ID,
                Const.BeeCloud.APP_Secret);
//        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, Const.BeeCloud.WECHAT_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    private void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("action", PayOrderitem.optional.action);
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("disable_pay_channels", "credit_group");
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
//            BCPay.getInstance(PayTypeActivity.this).reqAliPaymentAsync(
//                    PayOrderitem.title,
//                    PayOrderitem.order_money * 100,
//                    PayOrderitem.notice_sn,
//                    mapOptional,
//                    bcCallback);
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    null,
                    bcCallback);
        } else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {

//                BCPay.getInstance(this).reqWXPaymentAsync(
//                        PayOrderitem.title,               //订单标题
//                        PayOrderitem.order_money * 100,  //金额
//                        PayOrderitem.notice_sn,  //订单流水号
//                        mapOptional,            //扩展参数(可以null)
//                        bcCallback);            //支付完成后回调入口
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        null,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }


    private static class PayHandler extends Handler {
        WeakReference<PacketRechargeActivity> mActivityReference;

        PayHandler(PacketRechargeActivity activity) {
            mActivityReference = new WeakReference<PacketRechargeActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final PacketRechargeActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);

            /*
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
            */
        }
    };
}
